import React, { createContext, useState, PropsWithChildren, useRef } from 'react';
import { TreeDataNode } from "antd";
export type PropertiesTreeNode = TreeDataNode & {
  parentId?: string
}

// type CompApiPropsItem = {fields: Record<string, string>[]}
// type CompApiProps = {
//   [key:string]: CompApiPropsItem
// }
interface LowCodePageProviderProps {
  contextProperties: {
    [key:string]: PropertiesTreeNode
  }, //组件上下文属性
  setContextProperties: (id: string, properties: TreeDataNode)=>void,
  componentRefs: React.RefObject<Record<string, any>>,
  // compApiProps: CompApiProps, //Table or Form 设置了api可以把获取的fields数据存在这里
  // setCompApiProps: (id: string, props: CompApiPropsItem)=>void,
}
const LowCodePageContext = createContext<LowCodePageProviderProps>({
  contextProperties:{},
  setContextProperties:()=>{},
  componentRefs:{current:{}},
  // compApiProps:{},
  // setCompApiProps:()=>{}
});

const LowCodePageProvider = ({children}: PropsWithChildren) => {
  const [contextProperties, setContextPropertiesRaw] = useState({});

  const setContextProperties = (id: string, properties: TreeDataNode)=>{
    setContextPropertiesRaw(contextProperties=>({...contextProperties, [id]: properties}))
  }

  const componentRefs = useRef<Record<string, any>>({});

  // const [compApiProps, setCompApiPropsRaw] = useState<CompApiProps>({})
  // const setCompApiProps = (id: string, props: CompApiPropsItem)=>{
  //   const originData = compApiProps?.[id] || {}
  //   setCompApiPropsRaw(compApiProps=>({...compApiProps, [id]: {...originData, ...props}}))
  // }

  const value = { contextProperties, setContextProperties, componentRefs};
  return (
    <LowCodePageContext.Provider value={value}>
      {children}
    </LowCodePageContext.Provider>
  );
};

export { LowCodePageContext, LowCodePageProvider };